//
//  YCForgetPasswordViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/7.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  忘记密码

#import "YCForgetPasswordViewController.h"
#import "YCForgetPasswordEnsureViewController.h"
#import "YCForgetPasswordTextField.h"

static NSInteger timeDecCount = 60;

@interface YCForgetPasswordViewController ()<UITextFieldDelegate>

/** scrollView  */
@property (nonatomic, strong) UIScrollView *scrollView;
/** contentView  */
@property (nonatomic, strong) UIView *contentView;

///忘记密码标题
@property (nonatomic,readonly) UILabel *forgetPwdLabel;
///注册手机号
@property (nonatomic,readonly) UITextField *registerPhoneField;
///验证码
@property (nonatomic,readonly) YCForgetPasswordTextField *verificationCodeField;
///提示标题
@property (nonatomic,readonly) UILabel *tipsLabel;
///提交按钮
@property (nonatomic,readonly) UIButton *commitButton;
///返回按钮
@property (nonatomic,readonly) UIButton *backButton;
///rightView
@property (nonatomic,readonly) UIButton *rightViewButton;

/** 定时器  */
@property (nonatomic, weak) NSTimer *timer;

/** 记录当前响应view转到window的frame  */
@property (nonatomic, assign) CGRect firstResponseViewFrameOfWindow;

@end

@implementation YCForgetPasswordViewController

@synthesize forgetPwdLabel = _forgetPwdLabel;
@synthesize registerPhoneField = _registerPhoneField;
@synthesize verificationCodeField = _verificationCodeField;
@synthesize tipsLabel = _tipsLabel;
@synthesize commitButton = _commitButton;
@synthesize backButton = _backButton;
@synthesize rightViewButton = _rightViewButton;



#pragma mark - 懒加载
// 忘记密码
- (UILabel *)forgetPwdLabel
{
    if(!_forgetPwdLabel)
    {
        _forgetPwdLabel = [[UILabel alloc] init];
        _forgetPwdLabel.text = @"忘记密码";
        _forgetPwdLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _forgetPwdLabel.textAlignment = NSTextAlignmentCenter;
        _forgetPwdLabel.font = [UIFont systemFontOfSize:24];
    }
    return _forgetPwdLabel;
}

// 注册手机号
- (UITextField *)registerPhoneField
{
    if(!_registerPhoneField)
    {
        _registerPhoneField = [[UITextField alloc] init];
        _registerPhoneField.layer.borderWidth = 1;
        _registerPhoneField.layer.borderColor = [UIColor yc_colorWithUInt:0xe0e0e0].CGColor;
        _registerPhoneField.layer.cornerRadius= 17.5;
        _registerPhoneField.layer.masksToBounds = YES;
        _registerPhoneField.font = [UIFont systemFontOfSize:15];
        _registerPhoneField.backgroundColor = [UIColor whiteColor];
        _registerPhoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _registerPhoneField.placeholder = NSLocalizedString(@"请输入注册手机号", nil);//有默认颜色
        _registerPhoneField.returnKeyType = UIReturnKeyNext;
        _registerPhoneField.keyboardType = UIKeyboardTypeNumberPad;
        _registerPhoneField.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _registerPhoneField.delegate = self;

        
        //leftView
        UILabel *tipLabel = [[UILabel alloc] init];
        tipLabel.font = [UIFont boldSystemFontOfSize:15];
        CGSize tipLabelSize = [@"注册手机号" yc_sizeWithFont:tipLabel.font MaxSize:CGSizeMake(CGFLOAT_MAX, 0)];
        tipLabel.frame = CGRectMake(17, 0, tipLabelSize.width + 34, 40);
        tipLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        tipLabel.text = NSLocalizedString(@"注册手机号", nil);
        tipLabel.textAlignment = NSTextAlignmentCenter;
        _registerPhoneField.leftView = tipLabel;
        _registerPhoneField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _registerPhoneField;
}

- (UITextField *)verificationCodeField
{
    if(!_verificationCodeField)
    {
        _verificationCodeField = [[YCForgetPasswordTextField alloc] init];
        _verificationCodeField.delegate = self;
        
        _rightViewButton = _verificationCodeField.rightViewBtn;
        [self.rightViewButton setTitleColor:[UIColor blueColor] forState:UIControlStateDisabled];//失能时
        [_rightViewButton addTarget:self action:@selector(getVerificationCode) forControlEvents:UIControlEventTouchUpInside];
    }
    return _verificationCodeField;
}

// 接收短信大约需要60s
- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
        _tipsLabel = [[UILabel alloc] init];
        _tipsLabel.text = @"接收短信大约需要60s";
        _tipsLabel.textColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
        _tipsLabel.font = [UIFont systemFontOfSize:13];
    }
    return _tipsLabel;
}

- (UIButton *)commitButton
{
    if(!_commitButton)
    {
        _commitButton = [[UIButton alloc] init];
        _commitButton.titleLabel.font = [UIFont boldSystemFontOfSize:15];
        [_commitButton setTitleColor:[UIColor yc_colorWithUInt:0x3d3e40] forState:UIControlStateNormal];
        _commitButton.backgroundColor = [UIColor yc_colorWithUInt:0xf8bb36];
        _commitButton.layer.cornerRadius = 17.5;
        [_commitButton setTitle:NSLocalizedString(@"提交", nil) forState:UIControlStateNormal];
        [_commitButton addTarget:self action:@selector(didTouchUpInsideCommitButton:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _commitButton;
}

- (UIButton *)backButton
{
    if(!_backButton)
    {
        _backButton = [[UIButton alloc] init];
        _backButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _backButton.backgroundColor = [UIColor yc_colorWithUInt:0x3d3e40];
        _backButton.layer.cornerRadius = 17.5;
        [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_backButton setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(didTouchUpInsideBackButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (NSTimer *)timer
{
    if (!_timer) {
        //开始定时
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        [_timer setFireDate:[NSDate distantFuture]];//相当于暂停
        
    }
    return _timer;
}

#pragma mark - 生命周期

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self makeView];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    timeDecCount = 60;
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    //移除定时器
    [self.timer invalidate];
    self.timer = nil;
}
- (void)dealloc
{
    YCLogFunc
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)makeView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView.alwaysBounceVertical = YES;
    //    self.scrollView.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    self.scrollView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0);
    // 添加单击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScrollView:)];
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor yc_colorWithUInt:0xf7f7f7];
    self.contentView = contentView;
    [self.scrollView addSubview:contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.contentView addSubview:self.forgetPwdLabel];
    [self.contentView addSubview:self.registerPhoneField];
    [self.contentView addSubview:self.verificationCodeField];
    [self.contentView addSubview:self.tipsLabel];
    [self.contentView addSubview:self.commitButton];
    [self.contentView addSubview:self.backButton];
    
    [_forgetPwdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        [YCAdapter performOtherBlock:^{
            make.top.equalTo(self.contentView).offset(150);
        } IPhone6Block:^{
            make.top.equalTo(self.contentView).offset(206);
        } IPhone6pBlock:^{
            make.top.equalTo(self.contentView).offset(220);
        }];
        
        make.centerX.equalTo(self.contentView);
        make.height.equalTo(@48);
    }];
    
    [_registerPhoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_forgetPwdLabel.mas_bottom).with.offset(heightFromIphone6Height(60));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@40);
    }];
    
    [_verificationCodeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_registerPhoneField.mas_bottom).with.offset(heightFromIphone6Height(20));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@40);
    }];
    
    [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_verificationCodeField.mas_bottom).with.offset(heightFromIphone6Height(29));
        make.centerX.equalTo(self.contentView);
        make.height.equalTo(@30);
    }];
    
    [_commitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tipsLabel.mas_bottom).with.offset(heightFromIphone6Height(41));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    // 里面内容设置了中心右对齐
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_commitButton.mas_bottom).offset(heightFromIphone6Height(41));
        make.centerX.equalTo(self.contentView);
        make.left.equalTo(self.contentView).offset(47);
        make.right.equalTo(self.contentView).offset(-47);
        make.height.equalTo(@36);
    }];
    
    [self.contentView layoutIfNeeded];
    CGFloat contentH = CGRectGetMaxY(_backButton.frame);
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.bottom.equalTo(_logoImageView.mas_bottom).offset(heightFromIphone6Height(63));
        make.bottom.equalTo(_backButton.mas_bottom).offset(kScreenHeight - contentH+64);
    }];
    self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.contentView.frame)-64);
}


#pragma mark -- 响应事件

- (void)getVerificationCode
{
    YCLog(@"获取验证码");
    self.rightViewButton.enabled = NO;//失能
    //开定时器
    [self.timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:0]];//立即开始
}

///提交按钮
- (void)didTouchUpInsideCommitButton:(UIButton *)button
{
    YCLog(@"提交");
    [self.view endEditing:YES];
    
    YCForgetPasswordEnsureViewController *vc = [[YCForgetPasswordEnsureViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    [SVProgressHUD showWithStatus:@"提交中..."];
    
    [SVProgressHUD dismissWithDelay:1];

}

///返回按钮
- (void)didTouchUpInsideBackButton:(UIButton *)button
{
    YCLogFunc
    [self.navigationController popViewControllerAnimated:YES];

}

///点击回弹键盘
- (void)tapScrollView:(UITapGestureRecognizer *)tap
{
    YCLogFunc
    [self.view endEditing:YES];
}

#pragma mark - UITextField delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == self.registerPhoneField)
    {
        [self.verificationCodeField becomeFirstResponder];
    }
    else
    {
        [self.commitButton sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
    return YES;
}

#pragma mark - 定时器计时

- (void)timerTick:(NSTimer *)timer
{
    [self.rightViewButton setTitle:[NSString stringWithFormat:@"剩余:%zd秒",timeDecCount] forState:UIControlStateDisabled];
    timeDecCount--;
    if (timeDecCount == 0) {
        self.rightViewButton.enabled = YES;
        timeDecCount = 60;
        [self.timer setFireDate:[NSDate distantFuture]];//暂停
        [self.rightViewButton setTitle:@"再次发送" forState:UIControlStateNormal];
    }
    YCLogFunc
}

#pragma mark - 通知回调

///键盘将要弹出通知回调
- (void)receiveKeyboardWillChangeFrameNotification:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
   
    // 获取当前第一响应view
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIView *firstResponseView = [keyWindow performSelector:@selector(firstResponder)];
    
    _firstResponseViewFrameOfWindow = [self.view convertRect:firstResponseView.frame toView:keyWindow];
    if(rect.origin.y < kScreenHeight)//键盘上弹了
    {
        CGFloat offset = CGRectGetMaxY(_firstResponseViewFrameOfWindow) - CGRectGetMinY(rect)+15;//高出15
        if(offset < 0 ) return;
        rect = self.view.bounds;
        rect.origin.y = (offset);
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = rect;
        }];
    }
    else
    {
        [UIView animateWithDuration:duration animations:^{
            self.view.bounds = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }];
    }

}



@end
